/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.rpt.web;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportCSV;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.biz.rpt.entity.BizInitialStorage;
import com.thinkgem.jeesite.modules.biz.rpt.service.BizInitialStorageRptService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.LogUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 期初入库信息
 * @author xuchen
 * @version 2018-10-17
 */
@Controller
@RequestMapping(value = "${adminPath}/biz/rpt/bizInitialStorage")
public class BizInitialStorageRptController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
	@Autowired
	private BizInitialStorageRptService bizInitialStorageRptService;

	@RequiresPermissions("biz:bizInitialStorage:view")
	@RequestMapping(value = {"list"})
	public String list(BizInitialStorage bizInitialStorage, HttpServletRequest request, HttpServletResponse response, Model model) {

		Date stockInDateStart = bizInitialStorage.getStockInDateStart();
		Date stockInDateEnd = bizInitialStorage.getStockInDateEnd();

		Page<BizInitialStorage> page = bizInitialStorageRptService.findPage(new Page<BizInitialStorage>(request, response), bizInitialStorage);
		if(page != null){
			model.addAttribute("page",page);
		}

		List<BizInitialStorage> allList = bizInitialStorageRptService.findAllListByDate(stockInDateStart, stockInDateEnd,
				bizInitialStorage.getGoodsCode(),bizInitialStorage.getClassifyId());
		if(allList != null && allList.size() > 0){
			Integer sumNum = 0;
			for (BizInitialStorage initialStorage : allList) {
				if(initialStorage != null && initialStorage.getNumber() != null){
					sumNum += initialStorage.getNumber();
				}
			}
			model.addAttribute("sumNum",sumNum);
		}
		return "modules/biz/rpt/bizInitialStorage";
	}

	/**
	 * 导出
	 * @author xuchen
	 * @date 2018/10/22
	 * @param
	 * @return
	 */
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(BizInitialStorage bizInitialStorage, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		// 导出完毕提示的消息
		String msg = "";
		//记录日志操作
		String startOperation="开始进行期初出库报表数据导出操作！";
		String endOperation="期初出库报表数据导出操作结束！";
		User user = UserUtils.getUser();
		try {

			String fileNamePrefix = DateUtils.getDate("yyyyMMddHHmmss");// 导出文件名前缀

			List<String> fileNames = new ArrayList<String>(); // 存放生成的文件名称

			String exportDir = FileUtils.path(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + user.getId()
					+ "/files/exportFiles/" + DateUtils.getDate("yyyy-MM-dd") + "/");

			String filePath = exportDir + fileNamePrefix + "/";// 导出文件子目录

			if (!new File(filePath).exists()) {
				new File(filePath).mkdirs();
			}

			String zipFileName = fileNamePrefix + ".zip";// 压缩文件名称
			String zipFilePath = exportDir + zipFileName;// 压缩文件路径

			// 根据查询条件查询
			Page<BizInitialStorage> page = new Page<BizInitialStorage>();

			// 需要导出的数据总数目
			int dataSize = 0;
			try {
				// 获取商品列表的导出总条数
				page = bizInitialStorageRptService.findPage(new Page<BizInitialStorage>(), bizInitialStorage);
				if(page != null && page.getList() != null){
					dataSize = page.getList().size();
				}
			} catch (Exception e) {
				log.info("获取导出的数据总数目失败！失败信息：" + e.getMessage());
				LogUtils.saveLog(request, null, e, "获取导出的数据总数目失败！");
			}

			if (dataSize == 0) {
				msg = "导出失败！失败信息：导出数据为空";
				addMessage(redirectAttributes, "导出失败！失败信息：导出数据为空");
				log.info("导出失败！失败信息：导出数据为空");
				LogUtils.saveLog(request, user.getName() + "导出失败！失败信息：导出数据为空");
				return "redirect:" + Global.getAdminPath() + "/biz/rpt/bizInitialStorage/list";
			} else {// 5000数据分一个文件
				int fileSize = StringUtils.isBlank(Global.getConfig("exportExcel.fileSize")) ? 5000
						: Integer.parseInt(Global.getConfig("exportExcel.fileSize"));
				int fileNo = dataSize / fileSize + 1;
				for (int i = 1; i <= fileNo; i++) {
					page = bizInitialStorageRptService.findPage(new Page<BizInitialStorage>(i,fileSize), bizInitialStorage);
					String fileName = fileNamePrefix + "-" + String.valueOf(i) + ".csv";
					fileNames.add(fileName);
					new ExportCSV(BizInitialStorage.class, 1).setDataList(page.getList()).writeFile(filePath + fileName);

				}

				System.out.println("需要压缩的文件所在目录：" + filePath);
				System.out.println("压缩文件所在目录：" + exportDir);
				System.out.println("压缩文件名称：" + zipFilePath);

				log.info(startOperation);
				log.info("操作人：" + UserUtils.getUser().getName());
				log.info("预计导出数据共" + dataSize + "条");

				FileUtils.zipFiles(filePath, "", zipFilePath);
				FileUtils.delFile(filePath);
				msg = "导出成功！共导出数据：" + dataSize + "条。" + "文件只保留" + Global.getConfig("userfiles.life") + "天，请尽快到“"
						+ "<a href='" + request.getContextPath() + Global.getAdminPath()
						+ "/../static/ckfinder/ckfinder.html' style='color: white'>我的面板-文件管理</a>" + "”中下载！";
				addMessage(redirectAttributes,
						"导出成功！共导出数据：" + dataSize + "条。" + "文件只保留" + Global.getConfig("userfiles.life") + "天，请尽快到“"
								+ "<a href='" + request.getContextPath() + Global.getAdminPath()
								+ "/../static/ckfinder/ckfinder.html' style='color: white'>我的面板-文件管理</a>" + "”中下载！");
				log.info(endOperation);
				LogUtils.saveLog(request, user.getName() + "导出信息" + dataSize + "条");
			}
		} catch (Exception e) {
			msg = "导出失败！失败信息：" + e.getMessage();
			addMessage(redirectAttributes, "导出失败！失败信息：" + e.getMessage());
			log.info("导出失败！失败信息：" + e.getMessage());
			LogUtils.saveLog(request, null, e, user.getName() + "导出失败！");
		}
		return "redirect:" + Global.getAdminPath() + "/biz/rpt/bizInitialStorage/list";
	}

}